package com.kanshu.ksgb.fastread.doudou.module.personal.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseActivity;
import com.kanshu.ksgb.fastread.doudou.common.business.event.BindEvent;
import com.kanshu.ksgb.fastread.doudou.common.business.event.TaskEvent;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.UserUtils;
import com.kanshu.ksgb.fastread.doudou.common.net.INetCommCallback;
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult;
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.RetrofitHelper;
import com.kanshu.ksgb.fastread.doudou.common.util.StorageUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil;
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.UserInfo;
import com.kanshu.ksgb.fastread.doudou.module.personal.presenter.PersonCenterPresenter;
import com.kanshu.ksgb.fastread.doudou.module.personal.presenter.PersonCenterService;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

import static com.kanshu.ksgb.fastread.doudou.module.personal.activity.BindPhoneActivity.VALIDATION_EXPIRE_TIME;

/**
 * Created by xubo on 2018/10/22
 */

@SuppressLint("SetTextI18n")
@Route(path = ARouterConfig.PERSONAL_UPDATE_BIND_PHONE)
public class UpdateBindPhoneActivity extends BaseActivity {

    @BindView(R.id.send_checkcode)
    TextView mSendCheckcode;
    @BindView(R.id.input_phone)
    EditText mInputPhone;
    @BindView(R.id.invited_code)
    EditText mCode;

    PersonCenterPresenter mPresenter = new PersonCenterPresenter(lifeCyclerSubject);

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_bindphone);
        ButterKnife.bind(this);
        mTitle.setTitle("更换手机号码");
    }

    @OnClick({R.id.send_checkcode, R.id.sure_update})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.send_checkcode:
                if (TextUtils.isEmpty(mInputPhone.getText().toString()) || mInputPhone.getText().toString().length() != 11) {
                    ToastUtil.showMessage("输入的手机号码格式不正确");
                    return;
                }

                mSendCheckcode.setEnabled(false);
                RetrofitHelper helper = RetrofitHelper.getInstance();
                PersonCenterService personService = helper.createService(PersonCenterService.class);
                Map<String, String> map = new HashMap<>();
                map.put("phone", mInputPhone.getText().toString());
                personService.getValidateCode(map).compose(asyncRequest()).subscribe(new Observer<BaseResult<String>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        showLoading("");
                    }

                    @Override
                    public void onNext(BaseResult<String> stringBaseResult) {
                        if(stringBaseResult.result.status.code == 0){
                            ToastUtil.showMessage("获取验证码成功");
                            startCountDown();
                        }else{
                            ToastUtil.showMessage("获取验证码失败,请稍后再试");
                            mSendCheckcode.setEnabled(true);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtil.showMessage("获取验证码失败,请稍后再试");
                        e.printStackTrace();
                        mSendCheckcode.setEnabled(true);
                        dismissLoading();
                    }

                    @Override
                    public void onComplete() {
                        dismissLoading();
                    }
                });
                break;
            case R.id.sure_update:
                if (TextUtils.isEmpty(mInputPhone.getText().toString()) || mInputPhone.getText().toString().length() != 11) {
                    ToastUtil.showMessage("输入的手机号码格式不正确");
                    return;
                }
                if (TextUtils.isEmpty(mCode.getText().toString()) || mCode.getText().toString().length() != 4) {
                    ToastUtil.showMessage("输入的验证码格式不正确");
                    return;
                }
                showLoading("");
                mPresenter.changePhone(mInputPhone.getText().toString(), mCode.getText().toString(), new INetCommCallback<BaseResult<List<UserInfo>>>() {
                    @Override
                    public void onResponse(BaseResult<List<UserInfo>> result) {
                        dismissLoading();
                        if(result != null && result.result!= null) {
                            if(result.result.status.code == 0) {
                                StorageUtils.setPreference(UpdateBindPhoneActivity.this, Constants.SP_NAME, Constants.USER_BIND_PHONE + UserUtils.getUserId(), mInputPhone.getText().toString());
                                EventBus.getDefault().post(new TaskEvent(TaskEvent.BIND_PHONE));
                                BindEvent bindEvent = new BindEvent();
                                bindEvent.code = BindEvent.SUCCESS;
                                bindEvent.data = mInputPhone.getText().toString();
                                EventBus.getDefault().post(bindEvent);
                                Intent intent = new Intent();
                                intent.putExtra("phone", mInputPhone.getText().toString());
                                setResult(RESULT_OK, intent);
                                finish();
                            }else {
                                ToastUtil.showMessage(result.result.status.msg);
                            }
                        }
                    }

                    @Override
                    public void onError(int code, String errDesc) {
                        dismissLoading();
                        ToastUtil.showMessage(errDesc);
                    }
                });
                break;
        }
    }

    private void startCountDown() {
        Observable.intervalRange(1, VALIDATION_EXPIRE_TIME+1, 0,1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .takeUntil(lifeCyclerSubject)
                .subscribe(aLong -> updateContDownView(VALIDATION_EXPIRE_TIME - aLong));
    }

    private void updateContDownView(Long timeLeft) {
        if(timeLeft <= 0){
            mSendCheckcode.setEnabled(true);
            mSendCheckcode.setText("获取验证码");
            return;
        }
        mSendCheckcode.setText(timeLeft+ "s");
    }
}
